/*
 * Copyright (c) 2024 Termony Co., Ltd. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "hdf_vuart.h"
#include "osal_mem.h"
#include "hdf_base.h"
#include "hdf_log.h"

#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "VUART_INIT"

static int32_t HDF_VuartBufferInit(struct VuartCb *vuartCb)
{
    vuartCb->data = HdfSbufObtainDefaultSize();
    if (vuartCb->data == NULL) {
        HDF_LOGE("%s: [%s] HdfSbufObtainDefaultSize is failed.", __func__, vuartCb->cfg.name);
        return HDF_FAILURE;
    }

    DListHeadInit(&(vuartCb->recv));
    if (OsalMutexInit(&(vuartCb->rxMux)) != HDF_SUCCESS) {
        HDF_LOGE("%s: [%s] OsalMutexInit is failed.", __func__, vuartCb->cfg.name);
        return HDF_FAILURE;
    }

    if (OsalMutexInit(&(vuartCb->txMux)) != HDF_SUCCESS) {
        HDF_LOGE("%s: [%s] OsalMutexInit is failed.", __func__, vuartCb->cfg.name);
        return HDF_FAILURE;
    }

    return HDF_SUCCESS;
}

static void HDF_VuartBufferDeInit(struct VuartCb *vuartCb)
{
    if (vuartCb->data) {
        HdfSbufRecycle(vuartCb->data);
    }
    if (vuartCb->rxMux.realMutex) {
        OsalMutexDestroy(&(vuartCb->rxMux));
    }
    if (vuartCb->txMux.realMutex) {
        OsalMutexDestroy(&(vuartCb->txMux));
    }
}

int32_t HDF_VuartInit(struct VuartCb *vuartCb)
{
    if (vuartCb->initFlag) {
        return HDF_SUCCESS;
    }

    if (HDF_VuartIsrRegister(vuartCb) != HDF_SUCCESS) {
        HDF_LOGE("%s: [%s] HDF_VuartIsrRegister is failed.", __func__, vuartCb->cfg.name);
        return HDF_FAILURE;
    }

    if (HDF_VuartBufferInit(vuartCb) != HDF_SUCCESS) {
        HDF_LOGE("%s: [%s] HDF_VuartBufferInit is failed.", __func__, vuartCb->cfg.name);
        HDF_VuartBufferDeInit(vuartCb);
        return HDF_FAILURE;
    }

    return HDF_SUCCESS;
}

int32_t HDF_VuartDeinit(struct VuartCb *vuartCb)
{
    HDF_VuartBufferDeInit(vuartCb);
    HDF_VuartIsrUnregister(vuartCb);
    return HDF_SUCCESS;
}